//
//  CTCFinanceTaxCircleVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/25.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCFinanceTaxCircleVC.h"
#import "CTCArticleListCell.h"
#import "CTCArticleDetailVC.h"
#import "CTCArticleModel.h"
#import "CTCArticleModel.h"
#import "CTCPublishArticleVC.h"
#import "MXScrollView.h"
#import "CTCMyArticleVC.h"
#import "CTCActivityDetailVC.h"
#import "CTCActivityForecastCell.h"
#import "CTCActivityModel.h"

@interface CTCFinanceTaxCircleVC ()<MXSegmentedPagerDelegate,
                                    MXSegmentedPagerDataSource,
                                    MXScrollViewDelegate,
                                    MXScrollViewDelegate,
                                    UITableViewDelegate,
                                    UITableViewDataSource
                                    >
{
    BOOL _isNeedReloadData;
}

@property (nonatomic, strong) MXSegmentedPager  * segmentedPager;
@property (nonatomic, strong) UITableView       * firstTableView;
@property (nonatomic, strong) UITableView       * secondTableView;
@property (nonatomic, strong) UITableView       * thirdTableView;
//@property (nonatomic, strong) UITableView       * tableView;
@property (nonatomic, strong) UIWebView        * webView;
/** <#strong属性注释#> */
//@property (nonatomic, strong) NSMutableArray *articleArr;

/** <#strong属性注释#> */
@property (nonatomic, strong) NSMutableArray *firstArticleArr;

/** <#strong属性注释#> */
@property (nonatomic, strong) NSMutableArray *secondArticleArr;
/** <#strong属性注释#> */
@property (nonatomic, strong) NSMutableArray *activityArr;

///** <#assign属性注释#> */
//@property (nonatomic, assign) NSInteger lastID;

/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger firstLastID;

/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger secondLastID;

/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger thirdLastID;

@end

@implementation CTCFinanceTaxCircleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = HEXCOLOR(0xF9F9F9);
    [self setupNav];
    self.firstLastID = 1;
    self.secondLastID = 1;
    self.thirdLastID = 1;
    
    [self.view addSubview:self.segmentedPager];
    
    [self configNavBar];
    
    [kNotificationCenter addObserver:self selector:@selector(deleteMyArticle:) name:kReloadArticleListNotification object:nil];
    
    [self loadNew];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_isNeedReloadData) {
        [self loadNew];
    }
}


- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.segmentedPager.frame = (CGRect){
        .origin.x       = 0.f,
        .origin.y       = 0.f,
        .size.width     = self.view.frame.size.width,
        .size.height    = self.view.frame.size.height
    };
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark <MXSegmentedPagerDelegate>

- (CGFloat)heightForSegmentedControlInSegmentedPager:(MXSegmentedPager *)segmentedPager {
    return 50;
}

- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didSelectViewWithTitle:(NSString *)title {
        NSLog(@"%ld page selected.", (long)segmentedPager.segmentedControl.selectedSegmentIndex);
    
    if ((segmentedPager.segmentedControl.selectedSegmentIndex == 0) && !(self.firstArticleArr.count)) {
        [self loadNew];
    }
    
    if ((segmentedPager.segmentedControl.selectedSegmentIndex == 1) && !(self.secondArticleArr.count)) {
        [self loadNew];
    }
    
    if ((segmentedPager.segmentedControl.selectedSegmentIndex == 2) && !(self.activityArr.count)) {
        [self loadNew];
    }
    
    if (segmentedPager.segmentedControl.selectedSegmentIndex >= 3) {
        [MBProgressHUD showTipMessageInWindow:@"敬请期待"];
        return;
    }
}

- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didScrollWithParallaxHeader:(MXParallaxHeader *)parallaxHeader {
        NSLog(@"progress %f", parallaxHeader.progress);
    
}

#pragma mark <MXSegmentedPagerDataSource>

- (NSInteger)numberOfPagesInSegmentedPager:(MXSegmentedPager *)segmentedPager {
    return 4;
//    return 2;
}

- (NSString *)segmentedPager:(MXSegmentedPager *)segmentedPager titleForSectionAtIndex:(NSInteger)index {
    return @[@"财税资讯", @"新政解读", @"活动预告", @"招聘猎头"][index];
    
//     return @[@"财税资讯", @"新政解读"][index];
}

- (UIView *)segmentedPager:(MXSegmentedPager *)segmentedPager viewForPageAtIndex:(NSInteger)index {
    
    UIView *thirdView = [[UIView alloc]init];
//    thirdView.backgroundColor = [UIColor whiteColor];
    UIView *fourthView = [[UIView alloc]init];
//    fourthView.backgroundColor = [UIColor blueColor];
    
    return @[self.firstTableView, self.secondTableView, self.thirdTableView, fourthView][index];
    
}

#pragma mark <UITableViewDelegate>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        CTCArticleListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCArticleListCell" forIndexPath:indexPath];
        if (self.firstArticleArr.count >= indexPath.row) {
            cell.articleModel = self.firstArticleArr[indexPath.row];
        }
        return cell;
        
    } else  if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 1) {
        CTCArticleListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCArticleListCell" forIndexPath:indexPath];
        
        if (self.secondArticleArr.count >= indexPath.row) {
            cell.articleModel = self.secondArticleArr[indexPath.row];
        }
        
        return cell;
        
    }  else  if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 2) {
        CTCActivityForecastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCActivityForecastCell" forIndexPath:indexPath];
        if (self.activityArr.count >= indexPath.row) {
            cell.activityModel = self.activityArr[indexPath.row];
        }
        
        return cell;
        
    }
    
    return nil;
}


#pragma mark <UITableViewDataSource>

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        return self.firstArticleArr.count;
    } else if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 1) {
        return self.secondArticleArr.count;
    }  else if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 2) {
        return self.activityArr.count;
    }
    
    return 0;
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 2) {
        CTCActivityModel *model = self.activityArr[indexPath.row];
        CTCActivityDetailVC *vc = [[CTCActivityDetailVC alloc]init];
        vc.activityModel = model;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    CTCArticleDetailVC *detailVC = [CTCArticleDetailVC viewControllerFromStoryboard];
    CTCArticleModel *model;
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        
        if (self.firstArticleArr.count >= indexPath.row) {
            model = self.firstArticleArr[indexPath.row];
        }
        
       
    }else {
        if (self.secondArticleArr.count >= indexPath.row) {
            model = self.secondArticleArr[indexPath.row];
        }
        
    }
    
    detailVC.articleModel = model;
    
    MPWeakSelf(self);
    detailVC.commentSuccessReturnBlcok = ^(){
        model.discussNum = model.discussNum + 1;
        if (weakself.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
            [weakself.firstTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        } else {
            [weakself.secondTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    };
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)loadNew
{
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        self.firstLastID = 1;
        [self.firstArticleArr removeAllObjects];
        [self.firstTableView.mj_footer resetNoMoreData];
    } else if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 1) {
        self.secondLastID = 1;
        [self.secondArticleArr removeAllObjects];
        [self.secondTableView.mj_footer resetNoMoreData];
    } else if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 2) {
        self.thirdLastID = 1;
        [self.activityArr removeAllObjects];
        [self.thirdTableView.mj_footer resetNoMoreData];
    }
    
    [self loadArticleListData];
}

- (void)loadMore
{
    DeLog(@"更多请求");
    [self loadArticleListData];
}


- (void)stopRefresh
{
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        !self.firstTableView.mj_header.isRefreshing ? : self.firstTableView.mj_header.endRefreshing;
        !self.firstTableView.mj_footer.isRefreshing ? : self.firstTableView.mj_footer.endRefreshing;
        
    } else   if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 1) {
        !self.secondTableView.mj_header.isRefreshing ? : self.secondTableView.mj_header.endRefreshing;
        !self.secondTableView.mj_footer.isRefreshing ? : self.secondTableView.mj_footer.endRefreshing;
        
    }  else if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 2)  {
        !self.thirdTableView.mj_header.isRefreshing ? : self.thirdTableView.mj_header.endRefreshing;
        !self.thirdTableView.mj_footer.isRefreshing ? : self.thirdTableView.mj_footer.endRefreshing;
        
    }
   
}


- (void)loadArticleListData
{
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 2) {
        [self loadActivityListData];
        return;
    }
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    
    paramDic[@"type"] = @"label";
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        paramDic[@"uuid"] = @"1";
        paramDic[@"pageIndex"] = @(self.firstLastID);
        paramDic[@"pageEnd"] = @(self.firstLastID+9);
    } else {
        paramDic[@"uuid"] = @"2";
        paramDic[@"pageIndex"] = @(self.secondLastID);
        paramDic[@"pageEnd"] = @(self.secondLastID+9);
    }
    
    DeLog(@"网络请求,当前的index:%ld, 请求参数:%@",(long)self.segmentedPager.segmentedControl.selectedSegmentIndex,paramDic);
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kArticleListUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject:%@",responseObject);
        [self stopRefresh];
        CTCArticleListModel *listModel = [CTCArticleListModel yy_modelWithJSON:responseObject];
        if ([listModel.code integerValue] == 1) {
            [MBProgressHUD hideHUD];

            if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
                
                if (!listModel.articleArr.count) {
                    self.firstTableView.mj_footer.state = MJRefreshStateNoMoreData;
                    return ;
                }
                
                [self.firstArticleArr addObjectsFromArray:listModel.articleArr];
                self.firstLastID += self.firstArticleArr.count;
                [self.firstTableView reloadData];
                
            } else {
                
                if (!listModel.articleArr.count) {
                    self.secondTableView.mj_footer.state = MJRefreshStateNoMoreData;
                    return ;
                }
                
                [self.secondArticleArr addObjectsFromArray:listModel.articleArr];
                self.secondLastID += self.secondArticleArr.count;
                [self.secondTableView reloadData];
            }
            
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if ([listModel.code integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error:%@",error);
        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }

    }];
}

- (void)setupNav
{
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"我的文章" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemClick)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
}

//- (void)leftBarButtonItemClick
//{
//    CTCMyArticleVC *vc = [[CTCMyArticleVC alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
//}


- (void)rightBarButtonItemClick
{
    CTCPublishArticleVC *vc = [[CTCPublishArticleVC alloc]init];
    CTCNavigationController *nav = [[CTCNavigationController alloc]initWithRootViewController:vc];
    MPWeakSelf(self);
    vc.pulicSuccessDismissBlock = ^(NSString *typeString){
        [weakself loadNew];
    };
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)configNavBar {
    UILabel *label = [[UILabel alloc]init];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(0, 0, App_Frame_Width, 40);
    label.text = @"财税圈";
    self.navigationItem.titleView =  label;
    
}

- (void)loadActivityListData {
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    paramDic[@"pageIndex"] = @(self.thirdLastID);
    paramDic[@"pageEnd"] = @(self.thirdLastID+9);
    
    [MBProgressHUD showAnimationHUD];
    
    DeLog(@"当前选中的Index++:%ld",(long)self.segmentedPager.segmentedControl.selectedSegmentIndex);
    [RequestTool POST:kActivityListUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"活动列表：responseObject:%@",responseObject);
        [self stopRefresh];
        CTCActivityListModel *listModel = [CTCActivityListModel yy_modelWithJSON:responseObject];
        if ([listModel.code integerValue] ==  1) {
            [MBProgressHUD hideHUD];
            if (!listModel.activityArr.count) {
                self.thirdTableView.mj_footer.state = MJRefreshStateNoMoreData;
                return ;
            }
            
            [self.activityArr addObjectsFromArray:listModel.activityArr];
            self.thirdLastID += self.activityArr.count;
            
            [self.thirdTableView reloadData];
            
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if ([listModel.code integerValue]== 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error:%@",error);
        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
        
    }];
}


//- (void)pagerView:(MXPagerView *)pagerView willMoveToPage:(UIView *)page atIndex:(NSInteger)index {
//    if ((self.segmentedPager.segmentedControl.selectedSegmentIndex == 1) && !(self.secondArticleArr.count)) {
//        [self loadNew];
//        return;
//    }
//    
//    if ((self.segmentedPager.segmentedControl.selectedSegmentIndex == 2) && !(self.activityArr.count)) {
//        [self loadNew];
//        return;
//    }
//    
//    
//    if (index >= 3) {
//        
//        [MBProgressHUD showTipMessageInWindow:@"敬请期待"];
//        return;
//    }
//}



- (MXSegmentedPager *)segmentedPager {
    if (!_segmentedPager) {
        _segmentedPager = [[MXSegmentedPager alloc] init];
        _segmentedPager.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedPager.segmentedControl.backgroundColor = [UIColor whiteColor];
        _segmentedPager.segmentedControl.selectionIndicatorHeight = 2;
        _segmentedPager.segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
        _segmentedPager.segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : HEXCOLOR(0x2079ef), NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
        _segmentedPager.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        _segmentedPager.segmentedControl.selectionIndicatorColor = HEXCOLOR(0x2079ef);
        _segmentedPager.bounces = NO;
        _segmentedPager.delegate    = self;
        _segmentedPager.dataSource  = self;
        [_segmentedPager.pager registerClass:[self.firstTableView class] forPageReuseIdentifier:@"tableView"];
    }
    return _segmentedPager;
}



- (UITableView *)firstTableView
{
    if (!_firstTableView) {
        _firstTableView = [[UITableView alloc] init];
        _firstTableView.delegate = self;
        _firstTableView.dataSource = self;
        _firstTableView.rowHeight = UITableViewAutomaticDimension;
        _firstTableView.estimatedRowHeight = 200;
        _firstTableView.showsVerticalScrollIndicator = YES;
        _firstTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        [_firstTableView registerNib:[UINib nibWithNibName:@"CTCArticleListCell" bundle:nil] forCellReuseIdentifier:@"CTCArticleListCell"];
        _firstTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
        _firstTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    }
    
    return _firstTableView;
}


- (UITableView *)secondTableView
{
    if (!_secondTableView) {
        _secondTableView = [self.segmentedPager.pager dequeueReusablePageWithIdentifier:@"tableView"];
        _secondTableView.delegate = self;
        _secondTableView.dataSource = self;
        _secondTableView.rowHeight = UITableViewAutomaticDimension;
        _secondTableView.estimatedRowHeight = 200;
        _secondTableView.showsVerticalScrollIndicator = NO;
        _secondTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        [_secondTableView registerNib:[UINib nibWithNibName:@"CTCArticleListCell" bundle:nil] forCellReuseIdentifier:@"CTCArticleListCell"];
        //
        _secondTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
        _secondTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    }
    
    return _secondTableView;
}

- (UITableView *)thirdTableView {
    if (!_thirdTableView) {
        _thirdTableView = [[UITableView alloc] init];
        _thirdTableView.delegate = self;
        _thirdTableView.dataSource = self;
        _thirdTableView.rowHeight = UITableViewAutomaticDimension;
        _thirdTableView.estimatedRowHeight = 300;
        _thirdTableView.showsVerticalScrollIndicator = NO;
        _thirdTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        [_thirdTableView registerNib:[UINib nibWithNibName:@"CTCActivityForecastCell" bundle:nil] forCellReuseIdentifier:@"CTCActivityForecastCell"];
        //
        _thirdTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
        _thirdTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
        
    }
    
    return _thirdTableView;
}



-(NSMutableArray *)firstArticleArr
{
    if (!_firstArticleArr) {
        _firstArticleArr = [NSMutableArray array];
    }
    
    return _firstArticleArr;
}


-(NSMutableArray *)secondArticleArr
{
    if (!_secondArticleArr) {
        _secondArticleArr = [NSMutableArray array];
    }
    
    return _secondArticleArr;
}


- (NSMutableArray *)activityArr {
    if (!_activityArr) {
        _activityArr = [NSMutableArray array];
    }
    
    return _activityArr;
}


- (void)deleteMyArticle:(NSNotification *)notification
{
    _isNeedReloadData = YES;
    [self.firstArticleArr removeAllObjects];
    [self.secondArticleArr removeAllObjects];
}

@end
